package com.atguigu.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.msmservice.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    JavaMailSenderImpl mailSender;

    //发送短信的方法
    @Override
    public boolean send(String phone,String templateCode, Map<String, Object> param) {
        if(StringUtils.isEmpty(phone)) return false;//判断手机号是否为空
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI4GAa1k68JkqHmrgVpfKG", "kTovjBoIu0sqie4yZmHGP5rIazXuuC");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers", phone);   //手机号
        request.putQueryParameter("SignName", "我的谷粒在线教育网站");    //申请的阿里云 签名名称
        request.putQueryParameter("TemplateCode", templateCode);    //申请的阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据，转换为json数据

        //最终发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    //发送邮件的方法
    @Override
    public boolean cendEmail(String email, String code) {
        if(StringUtils.isEmpty(email)) return false;//判断邮箱是否为空

        //设置发送验证码邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("good boy♂你的验证码到了");//标题
        mailMessage.setText("验证码是"+code+"，知道吗？知道就说yes♂ sir");//内容
        mailMessage.setTo(email);//接收人
        mailMessage.setFrom("1746939174@qq.com");//发送人

        //最终发送
        mailSender.send(mailMessage);

        return true;//由于不知到是否发送成功，默认成功
    }

}
